package com.wxy.channel;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.FileChannel;

/**
 * @author 47868
 */
public class channel方法 {
    public static void read(){
        try(FileChannel channel = new RandomAccessFile("test1.txt","r").getChannel()) {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int length = channel.read(buffer);
            buffer.flip();
            while (buffer.hasRemaining()) {
                System.out.print((char)buffer.get());
            }
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    public static void write() {
        try (FileChannel channel = new RandomAccessFile("text.txt", "rw").getChannel()) {
            ByteBuffer buffer = ByteBuffer.allocate(6);
            buffer.put("hello".getBytes());
            // 关键：将 limit 设为实际写入的长度（position 的值）
            buffer.limit(buffer.position());
            buffer.flip();
            while (buffer.hasRemaining()) {
                int n = channel.write(buffer);
                System.out.println("写入了" + n + "个数据");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    public static void transfer() {
        try(FileChannel source = new RandomAccessFile("test1.txt","r").getChannel();
            FileChannel target = new RandomAccessFile("text.txt","rw").getChannel()){
            source.transferTo(0, source.size(), target);
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    public static void main(String[] args) {
//        read();
//        write();
        transfer();
    }
}
